package ci.web;

import java.io.File;
import java.net.URL;

import ci.web.util.file.FsHandler;
import ci.web.util.file.FsWatcher;

/**
 * 脚本自动重新加载类
 * @author zhh
 */
class CiReload {

    private CiService service;
    private URL[] urls;
    private FsWatcher[] watchers;
    
    public CiReload(CiService service, URL[] urls) {
        this.service = service;
        this.urls = urls;
    }
    
    /**
     * 开始监控脚本文件变更事件
     */
    public void start(){
        FsHandler handler = new FsHandler() {
            @Override
            public void onModify(File file) {
                if(file.isFile())
                    CiReload.this.update();
            }
            @Override
            public void onDelete(File file) {
                    CiReload.this.update();
            }
            @Override
            public void onCreate(File file) {
                if(file.isFile())
                    CiReload.this.update();
            }
        };
        watchers = new FsWatcher[urls.length];
        for(int i=0;i<urls.length;i++){
            URL url = urls[i];
            watchers[i] = new FsWatcher(new File(url.getPath()).getAbsolutePath(), handler);
            watchers[i].start();
        }
    }

    /**
     * 停止监控脚本目录变化
     */
    public void stop(){
        for(FsWatcher w : watchers){
            w.stop();
        }
    }
    /**
     * 脚本文件发生变化，重载路由
     */
    protected void update() {
        service.reload();
    }

}
